package com.daqian.chance.common.base;

import com.daqian.chance.common.constant.WebCommonConstant;
import com.daqian.chance.core.exception.UnauthorizedException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author: daqian
 * @date: 2019/7/25 14:09
 */
@Slf4j
public abstract class BaseController {

    protected HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    protected String getHeaderToken() {
        String token = this.getHttpServletRequest().getHeader(WebCommonConstant.TOKEN);
        return token;
    }

    protected HttpSession getSession() {
        return this.getHttpServletRequest().getSession();
    }

    /**
     * 删除session中的用户信息
     */
    protected void removeLoginUserInSession() {
        this.getSession().removeAttribute(WebCommonConstant.LOGIN_USER);
    }

    /**
     * 获取已登录的用户信息
     *
     * @param clazz
     * @param <T>
     * @return
     */
    protected <T> T getUser(Class<T> clazz) {
        T loginUser = (T) this.getSession().getAttribute(WebCommonConstant.LOGIN_USER);
        if (loginUser == null) {
            throw UnauthorizedException.msg("用户登录信息已失效");
        }
        return loginUser;
    }

}
